package com.example.demo.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;


public class JWTUtils {
    //token的时效
    private static long duration = 604800;
    //密钥
    private static String secretKey = "yousayrightbutyuanshenisaopenwor";

    /**
     * 简单生成token
     * 通过userid生成
     * @param userid subject
     * @return token
     */
    public static String generateToken (String userid){
        Date now = new Date();
        Date expiration  = new Date(now.getTime()+1000*duration);
        return Jwts.builder()
                .setHeaderParam("type","jwt")
                .setSubject(userid)
                .setIssuedAt(now)
                .setExpiration(expiration)
                .signWith(SignatureAlgorithm.HS512,secretKey)
                .compact();
    }

    /**
     * 解析token
     * @param token token
     * @return 解析结果
     */
    public static Claims getClaimsByToken(String token){
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(token)
                .getBody();
    }
}
